/*
 * @Description: 
 * @version: 
 * @Author: CoderXZ
 * @Date: 2019-02-14 09:18:59
 * @LastEditors: CoderXZ
 * @LastEditTime: 2020-06-27 21:48:03
 */

const base = require('base');
const view = require("render");

const app = {
    canvas: null,
    context: null,
    views: {},
    dataList: [],
    curView: null,
    curOffset: null,

    sentOpenIds: [],

    start: function () {

        this.sendOpenIds = [];
        this.canvas = wx.getSharedCanvas();
        this.context = this.canvas.getContext('2d');
        this.context.imageSmoothingEnabled = true;
        this.context.imageSmoothingQuality = "high";
        console.log("开放域初始化完毕");

        let self = this;

        wx.getUserCloudStorage({
            keyList: ["sentOpenIds"],
            success(res) {
                console.log("获取到当前玩家的数据sentOpenIds.", res);
                if (res.KVDataList.length <= 0) {
                    return
                }
                let cloudData = JSON.parse(res.KVDataList[0].value);
                self.sentOpenIds = cloudData.sendOpenIds;
                console.log("self.sentOpenIds:", self.sentOpenIds);
            },
            fail(res) { }
        });



        //微信像素  非标准像素
        wx.onTouchStart(e => {
            console.log("onTouchStart:", e);
            let pos = (e.type == 'touchstart') ? [e.touches[0].clientX, e.touches[0].clientY] : [null, null]

            if (!this.curView) {
                return;
            }
            let index = this.curView.checkIsFingerOnSendIcon(pos[0], pos[1]);
            console.log("index = ", index);
            if (index >= 0) {
                let itemData = this.dataList[index];
                console.log("itemData:", itemData);

                let toOpenId = itemData.openid;

                console.log("点击有效！！！");
                wx.modifyFriendInteractiveStorage({
                    key: '1',
                    opNum: 1,
                    operation: 'add',
                    toUser: toOpenId, // 好友的 openId
                    title: '送你 10 个金币，赶快打开游戏看看吧', // 2.9.0 支持
                    imageUrl: '', // 2.9.0 支持
                    success: function (res) {
                        console.log("修改好友互动数据 success,res:", res);

                        let timestamp = new Date().getTime();

                        self.sentOpenIds.push(toOpenId);

                        self.updateView();
                        let saveData = {
                            "wxgame": {
                                "score": self.sentOpenIds.length,
                                "update_time": timestamp
                            },
                            "sendOpenIds": self.sentOpenIds
                        }

                        wx.setUserCloudStorage({
                            KVDataList: [{
                                key: "sentOpenIds",
                                value: JSON.stringify(saveData)
                            }],
                            success: function (args) {
                                console.log("setUserCloudStorage 成功.", args);
                                // resolve(args);
                            },
                            fail: function (args) {
                                console.log("setUserCloudStorage 失败.", args);
                                // reject(args);
                            }
                        })
                    },
                    fail: function (res) {
                        console.log("修改好友数据失败，res:", res);
                    }
                })
            }
        });

        wx.onMessage(msg => {
            console.log("subContext receive msg:", msg);
            switch (msg.what) {
                case "action_init_context":
                    {
                        if (msg.arguments.view) {
                            const bound = msg.arguments.bound;

                            if (!bound || !bound.hasOwnProperty("width") || !bound.hasOwnProperty("height")) {
                                console.error(`子域绘制:${msg.arguments.view}, 未设置bound,无法正常绘制`);
                                return;
                            }

                            if (!this.views[msg.arguments.view]) {
                                this.views[msg.arguments.view] = new view.view(this.context, bound.left || 0, bound.top || 0, bound.width || 100, bound.height || 100);
                                let configPath = msg.arguments.view;
                                if (msg.arguments.view.indexOf("/") < 0) {
                                    configPath = "pages/" + configPath;
                                }

                                let scaleX = msg.arguments.scaleX;
                                let scaleY = msg.arguments.scaleY;
                                let startPos = msg.arguments.startPos;

                                this.curView = this.views[msg.arguments.view];
                                const config = require(configPath);
                                if (config) {
                                    this.views[msg.arguments.view].onConfig(config, bound.height, msg.arguments.spacingY || 1, scaleX, scaleY, startPos);
                                }
                            }
                        }


                        break;
                    }
                case "action_paging":
                    {
                        //翻页动作.
                        if (!msg.arguments.view) {
                            console.error("翻页参数未指定viewName");
                            return;
                        }
                        const render = this.views[msg.arguments.view];
                        if (!render) {
                            console.warn("排行榜页面还未初始化.");
                            return;
                        }

                        if (msg.arguments.offset) {
                            this.curOffset = msg.arguments.offset
                        }

                        if (msg.arguments.page !== null && undefined !== msg.arguments.page) {
                            render.setPage(msg.arguments.page, msg.arguments.offset, this.sentOpenIds);
                        }

                        if (msg.arguments.add) {
                            render.changePage(msg.arguments.add, msg.arguments.offset);
                        }
                        break;
                    }
                case "clear_content":
                    {
                        //todo
                        if (msg.what && this.views[msg.what]) {
                            const render = this.views[msg.what];
                            render.clearAll();
                            this.curView = null;
                            this.dataList = [];
                        }
                        break;
                    }
                case "show_input_list": //作为处理世界服数据消息
                    {
                        //todo
                        break;
                    }
                default:
                    {
                        if (msg.what && this.views[msg.what]) {
                            console.log("准备获取当前玩家数据:");
                            base.RankUtil.getSelfData(msg.arguments.key).then(selfData => {
                                base.RankUtil.getRankData(msg.arguments.key, msg.arguments.sortKey).then(data => {
                                    console.log("获取到当前玩家的排行数据:", data);

                                    base.RankUtil.filterSelfData(data, selfData);

                                    const render = this.views[msg.what];
                                    console.log("selfData:", selfData);
                                    render.render(data, selfData);
                                    this.dataList = data;
                                });
                            });
                        }
                        break;
                    }
            }
        })
    },

    updateView() {
        let curPage = this.curView.currPage;
        this.curView.setPage(curPage, this.curOffset, this.sentOpenIds);
    }

};
app.start();